package Bluetooth_NXT;

import java.io.DataOutputStream;
import java.io.IOException;

import lejos.nxt.*;
import lejos.nxt.comm.*;

public class NXTReceiver 
{
	private String _wait;
	private String _connect;
	private String _close;
	private NXTConnection _connection;
	private boolean _isConnected;
	private byte _visible = 1;
	private byte _invisible = 0;
	private DataOutputStream _write;
	
	public NXTReceiver()
	{
		_wait = "waiting...";
		_connect = "connected";
		_close = "closing...";
		_isConnected = false;
		if (!Bluetooth.getPower())
			Bluetooth.setPower(true);
		while(!Bluetooth.getPower()) {} //Wait until power is on
		if(Bluetooth.getVisibility() < 1) // 1 if visible, 0 if invisible
			Bluetooth.setVisibility(_visible); //Set visible
	}
	public void OpenConnection()
	{
		//Start Debug
		LCD.drawString(_wait, 0, 0);
		_connection = Bluetooth.waitForConnection();
		if (_connection != null)
			_isConnected = true;
		//Start Debug
		LCD.drawString(_connect, 0, 0);
		try{
			Thread.sleep(1000);
			}
			catch (InterruptedException e){}
			LCD.clear();
			//End Debug
	}
	public boolean IsConnected()
	{
		return _isConnected;
	}
	public void StartTalk()
	{
		if(_isConnected)
		{
			_connection.setIOMode(NXTConnection.RAW);
			byte[] b = new byte[]{1,2,3,4,5,6,7,8,9};//just for tests
			_write = _connection.openDataOutputStream();
			try
			{
				_write.write(b);
			}catch(IOException e){}
		}
	}
	public void FinishTalk()
	{
		if(_connection != null && _isConnected)
		{
			//Start Debug
			LCD.drawString(_close, 0, 0);
			try{
				Thread.sleep(1000);
				}
				catch (InterruptedException e){}
				//End Debug
			_connection.close();
			LCD.clear();
		}
	}
	public void DisconnectServer()
	{
		if(Bluetooth.getVisibility() > 0) // 1 if visible, 0 if invisible
			Bluetooth.setVisibility(_invisible); //Set invisible
		if (Bluetooth.getPower())
			Bluetooth.setPower(false);
	}
}
